library(tidyverse)
library(lme4)
library(lmerTest)
library(logging)
library(mvtnorm)
library(mgcv)
# Compute the log-likelihood of a new dataset using a fit lme4 model.
logLik_test <- function(lm, test_X, test_y) {
predictions <- predict(lm, test_X, re.form=NA)
# Get std.dev. of residual, estimated from train data
stdev <- sigma(lm)
# For each prediction--observation, get the density p(obs | N(predicted, model_sigma)) and reduce
density <- sum(dnorm(test_y, predictions, stdev, log=TRUE))
return(density)
}
# Get per-prediction log-likelihood
logLik_test_per <- function(lm, test_X, test_y) {
predictions <- predict(lm, test_X, re.form=NA)
# Get std.dev. of residual, estimated from train data
stdev <- sigma(lm)
# For each prediction--observation, get the density p(obs | N(predicted, model_sigma))
densities <- dnorm(test_y, predictions, stdev, log=TRUE)
return(densities)
}
# Compute MSE of a new dataset using a fit lme4 model.
mse_test <- function(lm, test_X, test_y) {
return(mean((predict(lm, test_X, re.form=NA) - test_y) ^ 2))
}
#Sanity checks
#mylm <- gam(psychometric ~ s(surprisal, bs = "cr", k = 20) + s(prev_surp, bs = "cr", k = 20) + te(freq, len, bs = "cr") + te(prev_freq, prev_len, bs = "cr"), data=train_data)
#c(logLik(mylm), logLik_test(mylm, train_data, train_data$psychometric))
#logLik_test(mylm, test_data, test_data$psychometric)
data = read.csv("../data/harmonized_results.csv")
all_data = data %>%
mutate(seed = as.factor(seed)) %>%
group_by(corpus, model, training, seed) %>%
mutate(prev_surp = lag(surprisal),
prev_code = lag(code),
prev_len = lag(len),
prev_freq = lag(freq),
prev_surp = lag(surprisal),
prev2_freq = lag(prev_freq),
prev2_code = lag(prev_code),
prev2_len = lag(prev_len),
prev2_surp = lag(prev_surp),
prev3_freq = lag(prev2_freq),
prev3_code = lag(prev2_code),
prev3_len = lag(prev2_len),
prev3_surp = lag(prev2_surp),
prev4_freq = lag(prev3_freq),
prev4_code = lag(prev3_code),
prev4_len = lag(prev3_len),
prev4_surp = lag(prev3_surp)) %>%
ungroup() %>%
# Filter back two for the dundee corpus. Filter back 1 for all other corpora
# NB this effectively removes all zero-surprisal rows, since early-sentence tokens don't have contiguous token history
filter((corpus == "dundee" & code == prev2_code + 2) | (corpus != "dundee" & code == prev4_code + 4)) %>%
select(-prev_code, -prev2_code, -prev3_code) %>%
drop_na()
all_data = all_data %>%
mutate(
model = as.character(model),
model = if_else(model == "gpt-2", "gpt2", model),
model = as.factor(model))
missing_rows = all_data %>% complete(nesting(corpus, code), nesting(model, training, seed)) %>%
group_by(corpus, code) %>%
filter(sum(is.na(surprisal)) > 0) %>%
ungroup() %>%
anti_join(all_data, by=c("corpus", "code", "model", "training", "seed"))
missing_rows %>% ggplot(aes(x=corpus, fill=factor(paste(model,training)))) + geom_bar(position=position_dodge(width=0.8))
print(missing_rows %>% group_by(model, training, seed, corpus) %>% summarise(n=n())) %>% arrange(desc(n))
# Compute the ideal number of model--seed--training observations per token.
to_drop = all_data %>%
group_by(corpus, code) %>% summarise(n = n()) %>% ungroup() %>%
group_by(corpus) %>% mutate( max_n = max(n)) %>% ungroup() %>%
filter(max_n != n) %>%
select(code, corpus)
#to_drop = all_data %>% group_by(corpus, code) %>% filter(n() != ideal_token_obs_count) %>% ungroup()
loginfo(paste("Dropping", nrow(to_drop), "observations corresponding to corpus tokens which are missing observations for some model."))
[0m2020-05-25 17:41:25 INFO::Dropping 10342 observations corresponding to corpus tokens which are missing observations for some model.[0m[0m[0m
loginfo(paste("Dropping", to_drop %>% group_by(corpus, code) %>% n_groups(), "tokens which are missing observations for some model."))
[0m2020-05-25 17:41:25 INFO::Dropping 10342 tokens which are missing observations for some model.[0m[0m[0m
all_data = all_data %>% anti_join(to_drop %>% group_by(corpus, code), by=c("corpus", "code"))
loginfo(paste("After drop,", nrow(all_data), "observations (", all_data %>% group_by(corpus, code) %>% n_groups(), " tokens) remain."))
[0m2020-05-25 17:41:26 INFO::After drop, 962274 observations ( 33117 tokens) remain.[0m[0m[0m
to_drop_zero_surps = all_data %>% group_by(corpus, code) %>% filter(any(surprisal == 0)) %>% ungroup()
loginfo(paste("Dropping", nrow(to_drop_zero_surps), "observations corresponding to corpus tokens which have surprisal zeros for some model."))
[0m2020-05-25 17:41:26 INFO::Dropping 116 observations corresponding to corpus tokens which have surprisal zeros for some model.[0m[0m[0m
loginfo(paste("Dropping", to_drop_zero_surps %>% group_by(corpus, code) %>% n_groups(), "tokens which have surprisal zeros for some model."))
[0m2020-05-25 17:41:26 INFO::Dropping 4 tokens which have surprisal zeros for some model.[0m[0m[0m
all_data = all_data %>% anti_join(to_drop_zero_surps %>% group_by(corpus, code), by=c("corpus", "code"))
loginfo(paste("After drop,", nrow(all_data), "observations (", all_data %>% group_by(corpus, code) %>% n_groups(), " tokens) remain."))
[0m2020-05-25 17:41:27 INFO::After drop, 962158 observations ( 33113 tokens) remain.[0m[0m[0m
to_drop_zero_psychs = all_data %>% group_by(corpus, code) %>% filter(any(psychometric == 0)) %>% ungroup()
loginfo(paste("Dropping", nrow(to_drop_zero_psychs), "observations corresponding to corpus tokens which have psychometric zeros for some model."))
[0m2020-05-25 17:41:27 INFO::Dropping 14935 observations corresponding to corpus tokens which have psychometric zeros for some model.[0m[0m[0m
loginfo(paste("Dropping", to_drop_zero_psychs %>% group_by(corpus, code) %>% n_groups(), "tokens which have psychometric zeros for some model."))
[0m2020-05-25 17:41:27 INFO::Dropping 515 tokens which have psychometric zeros for some model.[0m[0m[0m
all_data = all_data %>% anti_join(to_drop_zero_psychs %>% group_by(corpus, code), by=c("corpus", "code"))
loginfo(paste("After drop,", nrow(all_data), "observations (", all_data %>% group_by(corpus, code) %>% n_groups(), " tokens) remain."))
[0m2020-05-25 17:41:27 INFO::After drop, 947223 observations ( 32598 tokens) remain.[0m[0m[0m
# Compute linear model stats for the given training data subset and full test data.
# Automatically subsets the test data to match the relevant group for which we are training a linear model.
get_lm_data <- function(df, test_data, formula, fold, store_env) {
#this_lm <- gam(formula, data=df);
this_lm = lm(formula, data=df)
this_test_data <- semi_join(test_data, df, by=c("training", "model", "seed", "corpus"));
# Save lm to the global env so that we can access residuals later.
lm_name = paste(unique(paste(df$model, df$training, df$seed, df$corpus))[1], fold)
assign(lm_name, this_lm, envir=store_env)
summarise(df,
log_lik = as.numeric(logLik(this_lm, REML = F)),
test_lik = logLik_test(this_lm, this_test_data, this_test_data$psychometric),
test_mse = mse_test(this_lm, this_test_data, this_test_data$psychometric))
}
# For a previously fitted lm stored in store_env, get the residuals on test data of the relevant data subset.
get_lm_residuals <- function(df, fold, store_env) {
# Retrieve the relevant lm.
lm_name = paste(unique(paste(df$model, df$training, df$seed, df$corpus))[1], fold)
this_lm <- get(lm_name, envir=store_env)
mutate(df,
likelihood = logLik_test_per(this_lm, df, df$psychometric),
resid = df$psychometric - predict(this_lm, df, re.form=NA))
}
# Compute per-example delta-log-likelihood for the given test fold.
get_lm_delta_log_lik <- function(test_data, fold, baseline_env, full_env) {
lm_name = paste(unique(paste(test_data$model, test_data$training, test_data$seed, test_data$corpus))[1], fold)
baseline_lm <- get(lm_name, envir=baseline_env)
full_lm <- get(lm_name, envir=full_env)
delta_log_lik = logLik_test_per(full_lm, test_data, test_data$psychometric) - logLik_test_per(baseline_lm, test_data, test_data$psychometric)
return(cbind(test_data, delta_log_lik=delta_log_lik))
}
#####
# Define regression formulae.
# Eye-tracking regression: only use surprisal and previous surprisal; SPRT regression: use 2-back features.
#baseline_rt_regression = psychometric ~ te(freq, len, bs = "cr") + te(prev_freq, prev_len, bs = "cr") + te(prev2_freq, prev2_len, bs = "cr")
#baselie_sprt_regression = psychometric ~ te(freq, len, bs = "cr") + te(prev_freq, prev_len, bs = "cr") + te(prev2_freq, prev2_len, bs = "cr") + te(prev3_freq, prev3_len, bs = "cr") + te(prev4_freq, prev4_len, bs = "cr")
#full_rt_regression = psychometric ~ s(surprisal, bs = "cr", k = 20) + s(prev_surp, bs = "cr", k = 20) + s(prev2_surp, bs = "cr", k = 20) + te(freq, len, bs = "cr") + te(prev_freq, prev_len, bs = "cr") + te(prev2_freq, prev2_len, bs = "cr")
#full_sprt_regression = psychometric ~ s(surprisal, bs = "cr", k = 20) + s(prev_surp, bs = "cr", k = 20) + s(prev2_surp, bs = "cr", k = 20) + s(prev3_surp, bs = "cr", k = 20) + s(prev4_surp, bs = "cr", k = 20) + te(freq, len, bs = "cr") + te(prev_freq, prev_len, bs = "cr") + te(prev2_freq, prev2_len, bs = "cr") + te(prev3_freq, prev3_len, bs = "cr") + te(prev4_freq, prev4_len, bs = "cr")
baseline_rt_regression = psychometric ~ freq + prev_freq + prev2_freq + len + prev_len + prev2_len
baseline_sprt_regression = psychometric ~ freq + prev_freq + prev2_freq + prev3_freq + prev4_freq + len + prev_len + prev2_len + prev3_len + prev4_len
full_sprt_regression = psychometric ~ surprisal + prev_surp + prev2_surp + prev3_surp + prev4_surp + freq + prev_freq + prev2_freq + prev3_freq + prev4_freq + len + prev_len + prev2_len + prev3_len + prev4_len
full_rt_regression = psychometric ~ surprisal + prev_surp + prev2_surp + freq + prev_freq + prev2_freq + len + prev_len + prev2_len
#####
# Prepare frames/environments for storing results/objects.
baseline_results = data.frame()
full_model_results = data.frame()
baseline_residuals = data.frame()
full_residuals = data.frame()
log_lik_deltas = data.frame()
#Randomly shuffle the data
all_data<-all_data[sample(nrow(all_data)),]
#Create K equally size folds
K = 10
folds <- cut(seq(1,nrow(all_data)),breaks=K,labels=FALSE)
#Perform 10 fold cross validation
# Fit models for some fold of the data.
baseline_corpus = function(corpus, df, test_data, fold, env) {
if(corpus == "dundee") {
get_lm_data(df, test_data, baseline_rt_regression, fold, env)
} else {
get_lm_data(df, test_data, baseline_sprt_regression, fold, env)
}
}
full_model_corpus = function(corpus, df, test_data, fold, env) {
if(corpus[1] == "dundee") {
get_lm_data(df, test_data, full_rt_regression, fold, env)
} else {
get_lm_data(df, test_data, full_sprt_regression, fold, env)
}
}
# Prepare a new Environment in which we store fitted LMs, which we'll query later for residuals and other metrics.
baseline_env = new.env()
full_env = new.env()
for(i in 1:K) {
#Segement your data by fold using the which() function
testIndexes <- which(folds==i, arr.ind=TRUE)
test_data <- all_data[testIndexes, ]
train_data <- all_data[-testIndexes, ]
# Compute a baseline linear model for each model--training--seed--RT-corpus combination.
baselines = train_data %>%
group_by(model, training, seed, corpus) %>%
print(model) %>%
do(baseline_corpus(unique(.$corpus), ., test_data, i, baseline_env)) %>%
ungroup() %>%
mutate(seed = as.factor(seed),
fold = i)
baseline_results = rbind(baseline_results, baselines)
# Compute a full linear model for each model--training--seed-RT-corpus combination
full_models = train_data %>%
group_by(model, training, seed, corpus) %>%
do(full_model_corpus(unique(.$corpus), ., test_data, i, full_env)) %>%
ungroup() %>%
mutate(seed = as.factor(seed),
fold = i)
full_model_results = rbind(full_model_results, full_models)
# Compute delta-log-likelihoods
fold_log_lik_deltas = test_data %>%
group_by(model, training, seed, corpus) %>%
do(get_lm_delta_log_lik(., i, baseline_env, full_env)) %>%
ungroup()
log_lik_deltas = rbind(log_lik_deltas, fold_log_lik_deltas)
fold_baseline_residuals = test_data %>%
group_by(model, training, seed, corpus) %>%
do(get_lm_residuals(., i, baseline_env)) %>%
ungroup()
baseline_residuals = rbind(baseline_residuals, fold_baseline_residuals)
fold_full_residuals = test_data %>%
group_by(model, training, seed, corpus) %>%
do(get_lm_residuals(., i, full_env)) %>%
ungroup()
full_residuals = rbind(full_residuals, fold_full_residuals)
}
|===================================================================================================================================================== | 68% ~1 s remaining
|========================================================================================================================================================== | 70% ~1 s remaining
|================================================================================================================================================================= | 74% ~1 s remaining
|========================================================================================================================================================================= | 77% ~1 s remaining
|=========================================================================================================================================================================== | 78% ~1 s remaining
|=================================================================================================================================================================================== | 82% ~1 s remaining
|========================================================================================================================================================================================== | 85% ~0 s remaining
|================================================================================================================================================================================================== | 89% ~0 s remaining
|========================================================================================================================================================================================================= | 92% ~0 s remaining
|================================================================================================================================================================================================================= | 95% ~0 s remaining
|======================================================================================================================================================================================================================== | 99% ~0 s remaining
|============================================================================================== | 43% ~3 s remaining
|====================================================================================================== | 47% ~3 s remaining
|============================================================================================================= | 50% ~3 s remaining
|==================================================================================================================== | 53% ~2 s remaining
|============================================================================================================================ | 57% ~2 s remaining
|=================================================================================================================================== | 60% ~2 s remaining
|=========================================================================================================================================== | 64% ~2 s remaining
|================================================================================================================================================== | 67% ~2 s remaining
|========================================================================================================================================================== | 70% ~1 s remaining
|================================================================================================================================================================= | 74% ~1 s remaining
|=========================================================================================================================================================================== | 78% ~1 s remaining
|=================================================================================================================================================================================== | 82% ~1 s remaining
|========================================================================================================================================================================================== | 85% ~1 s remaining
|================================================================================================================================================================================================== | 89% ~0 s remaining
|========================================================================================================================================================================================================= | 92% ~0 s remaining
|================================================================================================================================================================================================================= | 95% ~0 s remaining
|======================================================================================================================================================================================================================== | 99% ~0 s remaining
|========================================================================================================================================================================= | 77% ~1 s remaining
|=========================================================================================================================================================================== | 78% ~1 s remaining
|=================================================================================================================================================================================== | 82% ~0 s remaining
|========================================================================================================================================================================================== | 85% ~0 s remaining
|================================================================================================================================================================================================== | 89% ~0 s remaining
|========================================================================================================================================================================================================= | 92% ~0 s remaining
|================================================================================================================================================================================================================= | 95% ~0 s remaining
|======================================================================================================================================================================================================================== | 99% ~0 s remaining
|============================================================================================================================================================ | 72% ~1 s remaining
|================================================================================================================================================================= | 74% ~1 s remaining
|==================================================================================================================================================================== | 75% ~1 s remaining
|========================================================================================================================================================================= | 77% ~1 s remaining
|=========================================================================================================================================================================== | 78% ~1 s remaining
|================================================================================================================================================================================ | 81% ~1 s remaining
|=================================================================================================================================================================================== | 82% ~1 s remaining
|======================================================================================================================================================================================== | 84% ~0 s remaining
|========================================================================================================================================================================================== | 85% ~0 s remaining
|=============================================================================================================================================================================================== | 88% ~0 s remaining
|================================================================================================================================================================================================== | 89% ~0 s remaining
|======================================================================================================================================================================================================= | 91% ~0 s remaining
|========================================================================================================================================================================================================= | 92% ~0 s remaining
|================================================================================================================================================================================================================= | 95% ~0 s remaining
|====================================================================================================================================================================================================================== | 98% ~0 s remaining
|======================================================================================================================================================================================================================== | 99% ~0 s remaining
|============================================================================================================================================================================== | 80% ~1 s remaining
|=================================================================================================================================================================================== | 82% ~0 s remaining
|========================================================================================================================================================================================== | 85% ~0 s remaining
|================================================================================================================================================================================================== | 89% ~0 s remaining
|========================================================================================================================================================================================================= | 92% ~0 s remaining
|================================================================================================================================================================================================================= | 95% ~0 s remaining
|======================================================================================================================================================================================================================== | 99% ~0 s remaining
|================================================================================================================================================================= | 74% ~1 s remaining
|==================================================================================================================================================================== | 75% ~1 s remaining
|====================================================================================================================================================================== | 76% ~1 s remaining
|=========================================================================================================================================================================== | 78% ~1 s remaining
|=================================================================================================================================================================================== | 82% ~1 s remaining
|========================================================================================================================================================================================== | 85% ~0 s remaining
|================================================================================================================================================================================================== | 89% ~0 s remaining
|========================================================================================================================================================================================================= | 92% ~0 s remaining
|================================================================================================================================================================================================================= | 95% ~0 s remaining
|======================================================================================================================================================================================================================== | 99% ~0 s remaining
|================================================================================================================================================================= | 74% ~1 s remaining
|========================================================================================================================================================================= | 77% ~1 s remaining
|============================================================================================================================================================================== | 80% ~1 s remaining
|=================================================================================================================================================================================== | 82% ~0 s remaining
|========================================================================================================================================================================================== | 85% ~0 s remaining
|================================================================================================================================================================================================== | 89% ~0 s remaining
|========================================================================================================================================================================================================= | 92% ~0 s remaining
|================================================================================================================================================================================================================= | 95% ~0 s remaining
|======================================================================================================================================================================================================================== | 99% ~0 s remaining
|============================================================================================================================================================================== | 80% ~1 s remaining
|=================================================================================================================================================================================== | 82% ~0 s remaining
|========================================================================================================================================================================================== | 85% ~0 s remaining
|================================================================================================================================================================================================== | 89% ~0 s remaining
|========================================================================================================================================================================================================= | 92% ~0 s remaining
|================================================================================================================================================================================================================= | 95% ~0 s remaining
|======================================================================================================================================================================================================================== | 99% ~0 s remaining
|============================================================================================================================================================================== | 80% ~1 s remaining
|=================================================================================================================================================================================== | 82% ~0 s remaining
|========================================================================================================================================================================================== | 85% ~0 s remaining
|================================================================================================================================================================================================== | 89% ~0 s remaining
|========================================================================================================================================================================================================= | 92% ~0 s remaining
|================================================================================================================================================================================================================= | 95% ~0 s remaining
|======================================================================================================================================================================================================================== | 99% ~0 s remaining
|========================================================================================================================================================== | 70% ~1 s remaining
|================================================================================================================================================================= | 74% ~1 s remaining
|========================================================================================================================================================================= | 77% ~1 s remaining
|=========================================================================================================================================================================== | 78% ~1 s remaining
|=================================================================================================================================================================================== | 82% ~1 s remaining
|========================================================================================================================================================================================== | 85% ~0 s remaining
|================================================================================================================================================================================================== | 89% ~0 s remaining
|========================================================================================================================================================================================================= | 92% ~0 s remaining
|================================================================================================================================================================================================================= | 95% ~0 s remaining
|====================================================================================================================================================================================================================== | 98% ~0 s remaining
|======================================================================================================================================================================================================================== | 99% ~0 s remaining
|============================================================================================================================================= | 65% ~1 s remaining
|================================================================================================================================================== | 67% ~1 s remaining
|========================================================================================================================================================== | 70% ~1 s remaining
|================================================================================================================================================================= | 74% ~1 s remaining
|====================================================================================================================================================================== | 76% ~1 s remaining
|=========================================================================================================================================================================== | 78% ~1 s remaining
|=================================================================================================================================================================================== | 82% ~1 s remaining
|========================================================================================================================================================================================== | 85% ~0 s remaining
|================================================================================================================================================================================================== | 89% ~0 s remaining
|========================================================================================================================================================================================================= | 92% ~0 s remaining
|================================================================================================================================================================================================================= | 95% ~0 s remaining
|======================================================================================================================================================================================================================== | 99% ~0 s remaining
|============================================================================================================================ | 57% ~2 s remaining
|=================================================================================================================================== | 60% ~1 s remaining
|=========================================================================================================================================== | 64% ~1 s remaining
|================================================================================================================================================== | 67% ~1 s remaining
|========================================================================================================================================================== | 70% ~1 s remaining
|================================================================================================================================================================= | 74% ~1 s remaining
|========================================================================================================================================================================= | 77% ~1 s remaining
|=========================================================================================================================================================================== | 78% ~1 s remaining
|=================================================================================================================================================================================== | 82% ~1 s remaining
|========================================================================================================================================================================================== | 85% ~1 s remaining
|================================================================================================================================================================================================== | 89% ~0 s remaining
|========================================================================================================================================================================================================= | 92% ~0 s remaining
|================================================================================================================================================================================================================= | 95% ~0 s remaining
|======================================================================================================================================================================================================================== | 99% ~0 s remaining
|====================================================================================================================================== | 61% ~1 s remaining
|=========================================================================================================================================== | 64% ~1 s remaining
|================================================================================================================================================== | 67% ~1 s remaining
|========================================================================================================================================================== | 70% ~1 s remaining
|============================================================================================================================================================ | 72% ~1 s remaining
|================================================================================================================================================================= | 74% ~1 s remaining
|=========================================================================================================================================================================== | 78% ~1 s remaining
|=================================================================================================================================================================================== | 82% ~1 s remaining
|========================================================================================================================================================================================== | 85% ~0 s remaining
|================================================================================================================================================================================================== | 89% ~0 s remaining
|========================================================================================================================================================================================================= | 92% ~0 s remaining
|================================================================================================================================================================================================================= | 95% ~0 s remaining
|======================================================================================================================================================================================================================== | 99% ~0 s remaining
|===========================================================================================================================================================================================================================|100% ~0 s remaining
|=========================================================================================================================================================================== | 78% ~1 s remaining
|=================================================================================================================================================================================== | 82% ~0 s remaining
|========================================================================================================================================================================================== | 85% ~0 s remaining
|================================================================================================================================================================================================== | 89% ~0 s remaining
|========================================================================================================================================================================================================= | 92% ~0 s remaining
|================================================================================================================================================================================================================= | 95% ~0 s remaining
|====================================================================================================================================================================================================================== | 98% ~0 s remaining
|======================================================================================================================================================================================================================== | 99% ~0 s remaining
|===========================================================================================================================================================================================================================|100% ~0 s remaining
|================================================================================================================================================================================================== | 89% ~0 s remaining
|========================================================================================================================================================================================================= | 92% ~0 s remaining
|================================================================================================================================================================================================================= | 95% ~0 s remaining
|======================================================================================================================================================================================================================== | 99% ~0 s remaining
|==================================================================================================================== | 53% ~2 s remaining
|============================================================================================================================ | 57% ~2 s remaining
|=================================================================================================================================== | 60% ~1 s remaining
|=========================================================================================================================================== | 64% ~1 s remaining
|================================================================================================================================================== | 67% ~1 s remaining
|======================================================================================================================================================= | 69% ~1 s remaining
|========================================================================================================================================================== | 70% ~1 s remaining
|================================================================================================================================================================= | 74% ~1 s remaining
|========================================================================================================================================================================= | 77% ~1 s remaining
|=========================================================================================================================================================================== | 78% ~1 s remaining
|=================================================================================================================================================================================== | 82% ~1 s remaining
|========================================================================================================================================================================================== | 85% ~1 s remaining
|================================================================================================================================================================================================== | 89% ~0 s remaining
|========================================================================================================================================================================================================= | 92% ~0 s remaining
|================================================================================================================================================================================================================= | 95% ~0 s remaining
|======================================================================================================================================================================================================================== | 99% ~0 s remaining
|=========================================================================================================================================================================== | 78% ~1 s remaining
|=================================================================================================================================================================================== | 82% ~0 s remaining
|========================================================================================================================================================================================== | 85% ~0 s remaining
|================================================================================================================================================================================================== | 89% ~0 s remaining
|========================================================================================================================================================================================================= | 92% ~0 s remaining
|================================================================================================================================================================================================================= | 95% ~0 s remaining
|======================================================================================================================================================================================================================== | 99% ~0 s remaining
|=========================================================================================================== | 49% ~2 s remaining
|============================================================================================================= | 50% ~2 s remaining
|==================================================================================================================== | 53% ~2 s remaining
|============================================================================================================================ | 57% ~2 s remaining
|=================================================================================================================================== | 60% ~2 s remaining
|=========================================================================================================================================== | 64% ~1 s remaining
|================================================================================================================================================== | 67% ~1 s remaining
|========================================================================================================================================================== | 70% ~1 s remaining
|================================================================================================================================================================= | 74% ~1 s remaining
|=========================================================================================================================================================================== | 78% ~1 s remaining
|=================================================================================================================================================================================== | 82% ~1 s remaining
|========================================================================================================================================================================================== | 85% ~1 s remaining
|================================================================================================================================================================================================== | 89% ~0 s remaining
|========================================================================================================================================================================================================= | 92% ~0 s remaining
|================================================================================================================================================================================================================= | 95% ~0 s remaining
|======================================================================================================================================================================================================================== | 99% ~0 s remaining
|=================================================================================================================================================================================== | 82% ~0 s remaining
|========================================================================================================================================================================================== | 85% ~0 s remaining
|================================================================================================================================================================================================== | 89% ~0 s remaining
|========================================================================================================================================================================================================= | 92% ~0 s remaining
|================================================================================================================================================================================================================= | 95% ~0 s remaining
|======================================================================================================================================================================================================================== | 99% ~0 s remaining
|================================================================================================================================================================= | 74% ~1 s remaining
|=========================================================================================================================================================================== | 78% ~1 s remaining
|=================================================================================================================================================================================== | 82% ~0 s remaining
|========================================================================================================================================================================================== | 85% ~0 s remaining
|================================================================================================================================================================================================== | 89% ~0 s remaining
|========================================================================================================================================================================================================= | 92% ~0 s remaining
|================================================================================================================================================================================================================= | 95% ~0 s remaining
|======================================================================================================================================================================================================================== | 99% ~0 s remaining
#write.csv(full_residuals, "../data/analysis_checkpoints/full_residuals.csv")
#write.csv(baseline_residuals, "../data/analysis_checkpoints/baseline_residuals.csv")
model_deltas = log_lik_deltas %>%
group_by(model, training, seed, corpus) %>%
summarise(mean_delta_log_lik = mean(delta_log_lik),
sem_delta_log_lik = sd(delta_log_lik) / sqrt(length(delta_log_lik)))
write.csv(full_model_results, "../data/analysis_checkpoints/full_model_result.csv")
write.csv(baseline_results, "../data/analysis_checkpoints/baseline_results.csv")
#full_model_results = read.csv("../data/analysis_checkpoints/ffull_model_results.csv")
#baseline_results = read.csv("../data/analysis_checkpoints/fbaseline_resultsb.csv")
metric <- "ΔLogLik"
#metric <- "-ΔMSE"
# # Select the relevant metric.
model_deltas = model_deltas %>%
# Retrieve the current test metric
mutate(delta_test_mean = mean_delta_log_lik,
delta_test_sem = sem_delta_log_lik) %>%
# mutate(delta_test_mean = mean_delta_mse,
# delta_test_sem = sem_delta_mse)
# Remove the raw metrics.
select(-mean_delta_log_lik, -sem_delta_log_lik,
#-mean_delta_mse, -sem_delta_mse
)
model_deltas
# Sanity check: training on train+test data should yield improved performance over training on just training data. (When evaluating on test data.)
# full_baselines = all_data %>%
# group_by(model, training, seed, corpus) %>%
# summarise(baseline_train_all_test_lik = logLik_test(lm(psychometric ~ len + freq + sent_pos, data=.), semi_join(test_data, ., by=c("training", "model", "seed", "corpus")), semi_join(test_data, ., by=c("training", "model", "seed", "corpus"))$psychometric)) %>%
# ungroup()
# full_baselines
#
# full_baselines %>%
# right_join(baselines, by=c("seed", "training", "model", "corpus")) %>%
# mutate(delta=baseline_train_all_test_lik-baseline_test_lik) %>%
# select(-baseline_lik) # %>%
# #select(-baseline_test_lik, -baseline_train_all_test_lik, -baseline_lik, -baseline_test_mse)
language_model_data = read.csv("../data/model_metadata.csv") %>%
mutate(model = as.character(model),
model = if_else(model == "gpt-2", "gpt2", model),
model = as.factor(model)) %>%
mutate(train_size = case_when(str_starts(training, "bllip-lg") ~ 42,
str_starts(training, "bllip-md") ~ 15,
str_starts(training, "bllip-sm") ~ 5,
str_starts(training, "bllip-xs") ~ 1),
# Training vocabulary usually covaries with the training corpus.
# But BPE models share a vocabulary across training corpora.
training_vocab=as.factor(ifelse(str_detect(training, "gptbpe"), "gptbpe", as.character(training))),
training_source=as.factor(str_replace(as.character(training), "-gptbpe", ""))
) %>%
mutate(seed = as.factor(seed)) %>%
select(-pid, -test_loss) %>%
distinct(model, training, seed, .keep_all = TRUE)
table(language_model_data$seed)
0 111 120 922 1111 3602 4301 7245 7877 28066 28068 44862 51272 64924 1581807512 1581807578 1581861474 1581955288 1582126320 1586986276 1587139950
4 7 6 5 4 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
table(model_deltas$seed)
111 120 607 922 1111 3602 4301 7245 7877 28066 28068 44862 51272 64924 1581807512 1581807578 1581861474 1581955288 1582126320 1586986276 1587139950
9 9 1 9 12 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
First join delta-metric data with model auxiliary data.
model_deltas = model_deltas %>%
merge(language_model_data, by = c("seed", "training", "model"), all=T) %>%
drop_na()
model_deltas
Also join on the original linear model data, rather than collapsing to delta-metrics. This will support regressions later on that don’t collapse across folds.
# Exclude ordered-neurons from all analyses.
model_deltas <- model_deltas %>%
filter(model != "ordered-neurons")
all_data %>% ggplot(aes(x=corpus)) + geom_bar()
print(all_data %>% group_by(corpus) %>% summarise(n=n()))
all_data %>%
ggplot(aes(x=freq, color=corpus)) + geom_density()
all_data %>%
ggplot(aes(x=len, color=corpus)) + geom_density()
all_data %>%
ggplot(aes(x=surprisal, color=corpus)) + geom_density()
model_deltas %>%
ggplot(aes(x=sg_score, y=delta_test_mean)) +
geom_errorbar(aes(ymin=delta_test_mean-delta_test_sem, ymax=delta_test_mean+delta_test_sem)) +
geom_smooth(method="lm", se=T) +
geom_point(stat="identity", position="dodge", alpha=1, size=3, aes(color=training_vocab, shape=model)) +
ylab(metric) +
xlab("Syntax Generalization Score") +
ggtitle("Syntactic Generalization vs. Predictive Power") +
scale_color_manual(values = c("bllip-lg"="#440154FF",
"bllip-md"="#39568CFF",
"bllip-sm"="#1F968BFF",
"bllip-xs"="#73D055FF",
"gptbpe"="#888888")) +
facet_grid(~corpus, scales="free") +
theme(axis.text=element_text(size=14),
strip.text.x = element_text(size=14),
legend.text=element_text(size=14),
axis.title=element_text(size=18),
legend.position = "bottom")
#ggsave("./cogsci_images/sg_loglik.png",height=5,width=6)
We control for effects of perplexity by relating the residuals of a performance ~ PPL regression to SG score.
x = d_resid %>%
filter(corpus == "natural-stories")
cor.test(x$resid.delta.mean, x$resid.sg.mean)
Pearson's product-moment correlation
data: x$resid.delta.mean and x$resid.sg.mean
t = -3.6328, df = 27, p-value = 0.001159
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
-0.7764391 -0.2613716
sample estimates:
cor
-0.5729883
do_stepwise_regression = function(cur_corpus) {
regression_data = model_deltas %>%
filter(corpus == cur_corpus)
print("----------------------")
print(cur_corpus)
lm1 = lm(delta_test_mean ~ training_vocab:test_ppl, data = regression_data)
lm2 = lm(delta_test_mean ~ training_vocab:test_ppl + sg_score, data = regression_data)
print(anova(lm1, lm2))
summary(lm2)
}
do_stepwise_regression("bnc-brown")
do_stepwise_regression("dundee")
do_stepwise_regression("natural-stories")
model_deltas %>%
mutate(test_ppl = if_else(test_ppl > 500, 329.9, test_ppl)) %>%
ggplot(aes(x=test_ppl, y=delta_test_mean, color=training_vocab, fill = training_vocab, ymin=0)) +
theme_bw() +
geom_text(aes(x=275, y=0, label = c("//"))) +
geom_errorbar(aes(ymin=delta_test_mean-delta_test_sem, ymax=delta_test_mean+delta_test_sem), alpha=0.4) +
#geom_smooth(method="lm", se=F) +
geom_point(stat="identity", position="dodge", alpha=1, size=4, aes(shape=model, color = training_vocab)) +
ylab(metric) +
xlab("Test Perplexity") +
#coord_cartesian(ylim = c(1, 16)) +
ggtitle("Test Perplexity vs. Predictive Power") +
scale_color_manual(values = c("bllip-lg"="#440154FF",
"bllip-md"="#39568CFF",
"bllip-sm"="#1F968BFF",
"bllip-xs"="#73D055FF",
"gptbpe"="#888888")) +
scale_shape_manual(values = c(16, 17, 15, 18)) +
scale_x_continuous(labels=c(0, 50, 100, 150, 200, 250, 500 ,550), breaks=c(0, 50, 100, 150, 200, 250, 300, 350), minor_breaks = NULL) +
scale_y_continuous(limits = c(0, NA), expand = c(0,0)) +
facet_wrap(~corpus, scales="free") +
coord_cartesian(clip="off") +
theme(axis.text=element_text(size=12),
strip.text.x = element_text(size=12),
legend.text=element_text(size=12),
axis.title=element_text(size=12),
legend.position = "right")
ggsave("../images/cuny2020/ppl_loglik.png",height=4.5,width=11)
dll_cor_test = function(df){
df %>%
summarise(
cor = cor.test(df$delta_test_mean, df$test_ppl)$estimate,
p = cor.test(df$delta_test_mean, df$test_ppl)$p.value
)
}
model_deltas %>%
filter(model != "5gram") %>%
group_by(training, corpus) %>%
mutate(n = n()) %>%
ungroup() %>%
filter(n > 2) %>%
group_by(training, corpus) %>%
do({ dll_cor_test(.) }) %>%
ungroup() %>%
arrange(corpus)
model_deltas %>%
mutate(train_size = log(train_size)) %>%
mutate(bpe = if_else(training_vocab == "gptbpe", "yes", "no"),
bpe = as.factor(bpe)) %>%
ggplot(aes(x=train_size, y=delta_test_mean, color=model)) +
theme_bw() +
geom_errorbar(aes(ymin=delta_test_mean-delta_test_sem, ymax=delta_test_mean+delta_test_sem), width = 0.1) +
geom_smooth(method="lm", se=T, alpha=0.2) +
geom_point(stat="identity", position="dodge", alpha=1, size=3, aes(shape=bpe)) +
ylab(metric) +
xlab("Log Million Training Tokens") +
ggtitle("Training Size vs. Predictive Power") +
facet_grid(.~corpus, scales="free") +
#scale_color_manual(values = c("#A42EF1", "#3894C8")) +
theme(axis.text=element_text(size=12),
strip.text.x = element_text(size=12),
legend.text=element_text(size=8),
legend.title=element_text(size=8),
axis.title=element_text(size=14),
legend.position = "bottom",
legend.direction = "horizontal",
legend.key.width = unit(0.3,"cm"),
legend.spacing.x = unit(0.1, 'cm'))
ggsave("../images/cuny2020/training_loglik.png",height=5,width=5)
model_cor_test = function(df){
df %>%
summarise(cor = cor.test(df$train_size, df$delta_test_mean)$estimate,
p = cor.test(df$train_size, df$delta_test_mean)$p.value)
}
model_deltas %>%
group_by(model, corpus) %>%
do({model_cor_test(.)}) %>%
ungroup() %>%
arrange()
model_deltas %>%
mutate(train_size = log(train_size)) %>%
mutate(bpe = if_else(training_vocab == "gptbpe", "yes", "no"),
bpe = as.factor(bpe)) %>%
ggplot(aes(x=train_size, y=sg_score, color=model)) +
theme_bw() +
geom_smooth(method="lm", se=T, alpha=0.2) +
geom_point(stat="identity", position="dodge", alpha=1, size=3, aes(shape=bpe)) +
ylab("SG SCore") +
xlab("Log Million Training Tokens") +
ggtitle("Training Size vs. SG Score") +
#scale_color_manual(values = c("#A42EF1", "#3894C8")) +
#facet_grid(~model, scales="free") +
theme(axis.text=element_text(size=12),
strip.text.x = element_text(size=12),
legend.text=element_text(size=8),
legend.title=element_text(size=8),
axis.title=element_text(size=14),
legend.position = "bottom",
legend.direction = "horizontal",
legend.key.width = unit(0.3,"cm"),
legend.spacing.x = unit(0.1, 'cm'))
ggsave("../images/cuny2020/training_sg.png",height=5,width=4)
model_cor_test = function(df){
df %>%
summarise(cor = cor.test(df$train_size, df$sg_score)$estimate,
p = cor.test(df$train_size, df$sg_score)$p.value)
}
model_deltas %>%
group_by(model) %>%
do({model_cor_test(.)}) %>%
ungroup()
all_data %>%
ggplot(aes(x=surprisal)) +
theme_bw() +
geom_density() +
facet_grid(~corpus) +
coord_cartesian(xlim = c(0, 21)) +
theme(panel.spacing = unit(2.5, "cm"))
ggsave("../images/cuny2020/surp_corr_marginals.png",height=1.5,width=11)
fit_gams = function(df, corpus, model, training){
print(paste(corpus, model, training))
if(corpus == "dundee") {
m = gam(psychometric ~ s(surprisal, bs = 'cr', k = 20) + s(prev_surp, bs = 'cr', k = 20) + te(freq, len, bs = 'cr') + te(prev_freq, prev_len, bs = 'cr'), data = df)
} else {
m = gam(psychometric ~ s(surprisal, bs = 'cr', k = 20) + s(prev_surp, bs = 'cr', k = 20) + s(prev2_surp, bs = 'cr', k = 20) + s(prev3_surp, bs = 'cr', k = 20) + te(freq, len, bs = 'cr') + te(prev_freq, prev_len, bs = 'cr') + te(prev2_freq, prev2_len, bs = 'cr') + te(prev3_freq, prev3_len, bs = 'cr'), data = df)
}
pdf(paste("../images/cuny2020/gam_fits/", corpus, "-", model, "-", training, ".pdf", sep=""))
plot(m, scale = 0, rug=T)
dev.off()
plotdata = visreg(m, type="contrast", plot=F)
smooths = ldply(plotdata, function(part) data.frame(variable = part$meta$x, surp=part$fit[[part$meta$x]], smooth=part$fit$visregFit, lower=part$fit$visregLwr, upper=part$fit$visregUpr)) %>%
mutate(model = model, corpus = corpus, training = training)
return(smooths)
}
smooths = all_data %>%
group_by(training, model, corpus) %>%
do({ fit_gams(., unique(.$corpus), unique(.$model), unique(.$training)) }) %>%
ungroup()
write.csv(smooths, "../data/gam_smooths.csv")
smooths %>%
filter(variable == "surprisal", training == "bllip-md") %>%
ggplot(aes(x=surp, y=smooth, color=training)) +
theme_bw() +
geom_line(size=1) +
geom_line(aes(y=lower), linetype="dashed") +
geom_line(aes(y=upper), linetype="dashed") +
facet_wrap(corpus~model, scales = "free")
ggsave("../images/cuny2020/gam_surp_corr.png", height=6,width=12)
all_data %>%
filter(model == "gpt2", corpus == "dundee") %>%
filter(surprisal<21) %>%
mutate(bpe=str_detect(training, "bpe"),
training_source=str_replace(training, "-gptbpe", "")) %>%
ggplot(aes(x=surprisal, y=psychometric, color=training_source, linetype=bpe)) +
theme_bw() +
#stat_smooth(se=T, alpha=0.5) +
geom_smooth(method = "gam", formula = psychometric ~ s(surprisal, bs = 'cr', k = 20) + s(prev_surp, bs = 'cr', k = 20) + te(freq, len, bs = 'cr') + te(prev_freq, prev_len, bs = 'cr', se = F)) +
#geom_errorbar(color="black", width=.2, position=position_dodge(width=.9), alpha=0.3) +
#geom_point(stat="identity", position="dodge", alpha=1, size=3) +
ylab("Processing Time (ms)") +
xlab("Surprisal (bits)") +
ggtitle("Surprisal vs. Reading Time / Gaze Duration") +
facet_wrap(model ~ corpus, scales="free", ncol=3, strip.position = c("right")) +
scale_color_manual(values = c("bllip-lg"="#440154FF",
"bllip-md"="#39568CFF",
"bllip-sm"="#1F968BFF",
"bllip-xs"="#73D055FF",
"bllip-lg-gptbpe"="#888888",
"bllip-md-gptbpe"="#888888",
"bllip-sm-gptbpe"="#888888",
"bllip-xs-gptbpe"="#888888")) +
coord_cartesian(xlim = c(0, 21)) +
theme(axis.text=element_text(size=10),
axis.text.y = element_text(size = 10),
strip.text.x = element_text(size=10),
legend.text=element_text(size=10),
axis.title=element_text(size=12),
legend.position = "right")
#ggsave("../images/cuny2020/surp_corr.png",height=6,width=12)
corr_test = function(df){
df %>%
summarise(
cor = cor.test(df$surprisal, df$psychometric)$estimate
)
}
all_data %>%
group_by(model, training, corpus, seed) %>%
do({ cor = corr_test(.)}) %>%
ungroup()
all_data %>%
#filter(surprisal < 15, surprisal > 0) %>%
filter(model == "vanilla") %>%
ggplot(aes(x=surprisal, y=psychometric)) +
#stat_smooth(se=T, alpha=0.5) +
#geom_errorbar(color="black", width=.2, position=position_dodge(width=.9), alpha=0.3) +
geom_point(alpha=0.1) + #stat="identity", position="dodge", alpha=1, size=3) +
ylab("Processing Time (ms)") +
xlab("Surprisal (bits)") +
ggtitle("Surprisal vs. Reading Time / Gaze Duration: Vanilla") +
facet_grid(corpus~training, scales = "free")
# scale_color_manual(values = c("bllip-lg"="#440154FF",
# "bllip-md"="#39568CFF",
# "bllip-sm"="#1F968BFF",
# "bllip-xs"="#73D055FF",
# "bllip-lg-gptbpe"="#888888",
# "bllip-md-gptbpe"="#888888",
# "bllip-sm-gptbpe"="#888888",
# "bllip-xs-gptbpe"="#888888"))
all_data %>%
filter(corpus == "dundee", model == "vanilla", training == "bllip-lg", surprisal > 20, psychometric < 300)
print(full_residuals %>% filter(corpus == "dundee", model == "vanilla", training == "bllip-lg") %>% arrange(desc(resid)))
full_residuals %>% filter(corpus == "dundee", model == "vanilla", training == "bllip-lg") %>% arrange(desc(resid)) %>% filter(resid > 150) %>%
ggplot(aes(x=surprisal)) + geom_density()
all_data %>%
#filter(surprisal < 15, surprisal > 0) %>%
filter(model == "rnng") %>%
ggplot(aes(x=surprisal, y=psychometric)) +
#stat_smooth(se=T, alpha=0.5) +
#geom_errorbar(color="black", width=.2, position=position_dodge(width=.9), alpha=0.3) +
geom_point(alpha=0.1) + #stat="identity", position="dodge", alpha=1, size=3) +
ylab("Processing Time (ms)") +
xlab("Surprisal (bits)") +
ggtitle("Surprisal vs. Reading Time / Gaze Duration: RNNG") +
facet_grid(corpus~training, scales = "free")
all_data %>%
filter(corpus == "dundee", model == "rnng", training == "bllip-lg", surprisal > 20, psychometric < 300)
print(full_residuals %>% filter(corpus == "dundee", model == "rnng", training == "bllip-lg") %>% arrange(desc(resid)))
full_residuals %>% filter(corpus == "dundee", model == "rnng", training == "bllip-lg") %>% arrange(desc(resid)) %>% filter(resid > 150) %>%
ggplot(aes(x=surprisal)) + geom_density()
ngram_resids = full_residuals %>% filter(model == "5gram", training == "bllip-sm") %>% group_by(corpus, code) %>% summarise(freq=mean(freq), psychometric=mean(psychometric), surprisal=mean(surprisal), resid=mean(resid))
vanilla_resids = full_residuals %>% filter(model == "vanilla", training == "bllip-sm") %>% group_by(corpus, code) %>% summarise(freq=mean(freq), psychometric=mean(psychometric), surprisal=mean(surprisal), resid=mean(resid))
resids_joined = ngram_resids %>% left_join(vanilla_resids, by=c("corpus", "code"), suffix=c(".ngram", ".vanilla"))
resids_joined %>%
ggplot(aes(x=resid.ngram, y=resid.vanilla)) + geom_point() + geom_abline(slope=1, color="red") +
facet_grid(~corpus)
resids_joined %>%
mutate(resid_diff=resid.ngram - resid.vanilla) %>%
ggplot(aes(x=resid_diff)) + geom_density() +
facet_grid(~corpus)
resids_joined %>%
mutate(resid_diff=abs(resid.ngram) - abs(resid.vanilla),
big=resid_diff < -10) %>%
ggplot(aes(x=surprisal.ngram, color=big)) + geom_density() + facet_grid(~corpus) +
ggtitle("ngram surprisal of high-improvement tokens (relative to vanilla)")
resids_joined %>%
mutate(resid_abs_diff=abs(resid.ngram - resid.vanilla)) %>%
ggplot(aes(x=freq.ngram, y=resid_abs_diff)) + geom_point(alpha=0.1) + geom_smooth()
gpt_resids = full_residuals %>% filter(model == "gpt2", training == "bllip-sm-gptbpe") %>% group_by(corpus, code) %>% summarise(freq=mean(freq), psychometric=mean(psychometric), surprisal=mean(surprisal), resid=mean(resid))
vanilla_resids = full_residuals %>% filter(model == "vanilla", training == "bllip-sm") %>% group_by(corpus, code) %>% summarise(freq=mean(freq), psychometric=mean(psychometric), surprisal=mean(surprisal), resid=mean(resid))
resids_joined = gpt_resids %>% left_join(vanilla_resids, by=c("corpus", "code"), suffix=c(".gpt", ".vanilla"))
resids_joined %>%
ggplot(aes(x=resid.gpt, y=resid.vanilla)) + geom_point() + geom_abline(slope=1, color="red") +
facet_grid(~corpus)
resids_joined %>%
mutate(resid_diff=resid.gpt - resid.vanilla) %>%
ggplot(aes(x=resid_diff)) + geom_density() +
facet_grid(~corpus)
resids_joined %>%
mutate(resid_diff=abs(resid.gpt) - abs(resid.vanilla),
big=resid_diff < -10) %>%
ggplot(aes(x=surprisal.gpt, color=big)) + geom_density() + facet_grid(~corpus) +
ggtitle("gpt surprisal of high-improvement tokens (relative to vanilla)")
resids_joined %>%
mutate(resid_abs_diff=abs(resid.gpt - resid.vanilla)) %>%
ggplot(aes(x=freq.gpt, y=resid_abs_diff)) + geom_point(alpha=0.1) + geom_smooth()
resid_deltas = full_residuals %>% right_join(baseline_residuals, by=c("corpus", "code", "model", "training", "seed"), suffix=c(".full", ".baseline")) %>%
select(resid.baseline, resid.full, code, surprisal.full, psychometric.full, model, training, seed, corpus, len.full) %>%
mutate(resid.baseline.pol = if_else(resid.baseline > 0, 1, 0),
resid.full.pol = if_else(resid.full > 0, 1, 0)) %>%
mutate(resid.baseline = abs(resid.baseline),
resid.full = abs(resid.full)) %>%
mutate(resid_delta=resid.baseline - resid.full, #positive is better
training_source=as.factor(str_replace(training, "-gptbpe", "")),
bpe=str_detect(training, "gptbpe"))
r = resid_deltas %>%
filter(resid.full.pol != resid.baseline.pol)
resid_deltas %>%
ggplot(aes(x=surprisal.full, y=resid_delta, color=training)) +
facet_grid(model~corpus) +
geom_point(alpha=0.1, size=0.5)
language_model_data %>% filter(model == "gpt2")
resid_deltas %>%
group_by(corpus) %>%
mutate(psychometric = scale(psychometric.full)) %>%
ungroup() %>%
ggplot(aes(x=psychometric)) +
theme_bw() +
geom_density() +
geom_vline(xintercept = 0, color = "grey") +
facet_grid(.~corpus) +
#coord_cartesian(xlim = c(-2, 4)) +
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank())
#ggsave("length.png", width = 8, height = 1)
log_lik_deltas %>%
#resid_deltas %>%
#filter(resid.full.pol == resid.baseline.pol) %>%
group_by(corpus) %>%
mutate(psychometric = scale(psychometric)) %>%
ungroup() %>%
#filter(psychometric < 4) %>%
#filter(len.full <= 10) %>%
ggplot(aes(x = psychometric, y = delta_log_lik, color = model)) +
theme_bw() +
facet_grid(. ~ corpus, scales = "free") +
#geom_rug(alpha = 0.003, sides = "b") +
geom_hline(yintercept=0, color = "blue") +
geom_vline(xintercept = 0, color = "grey") +
geom_smooth(se = T, alpha = 0.2) +
coord_cartesian(ylim = c(-0.1, 0.2), xlim = c(-2, 4)) +
theme(legend.position = "bottom",
strip.text.x = element_blank())
ggsave( "./resid_psycho.png", height = 4, width = 8)
resid_deltas %>%
group_by(corpus) %>%
mutate(psychometric = scale(psychometric.full)) %>%
ungroup() %>%
ggplot(aes(x=len.full)) +
theme_bw() +
geom_histogram(bins = 20) +
geom_vline(xintercept = 0, color = "grey") +
facet_grid(.~corpus) +
coord_cartesian(xlim = c(1, 10)) +
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank())
ggsave("length_maringals.png", width = 8, height = 1)
log_lik_deltas %>%
#resid_deltas %>%
#filter(resid.full.pol == resid.baseline.pol) %>%
group_by(corpus) %>%
mutate(psychometric = scale(psychometric)) %>%
ungroup() %>%
#filter(psychometric < 4) %>%
#filter(len.full <= 10) %>%
ggplot(aes(x = len, y = delta_log_lik, color = model)) +
theme_bw() +
facet_grid(. ~ corpus, scales = "free") +
#geom_rug(alpha = 0.003, sides = "b") +
geom_hline(yintercept=0, color = "blue") +
geom_vline(xintercept = 0, color = "grey") +
geom_smooth(se = T, alpha = 0.2) +
coord_cartesian(ylim = c(-0.02, 0.06), xlim = c(1, 10)) +
theme(legend.position = "bottom",
strip.text.x = element_blank())
ggsave( "./resid_length.png", height = 4, width = 8)
word_norm = log_lik_deltas %>%
drop_na() %>%
group_by(word, corpus, model, training, seed) %>%
mutate(psychoword = scale(psychometric),
norm_surp = scale(surprisal))
word_norm %>%
ggplot(aes(x=norm_surp)) +
facet_grid(~corpus) +
geom_density() +
coord_cartesian(xlim = c(-2, 5)) +
geom_vline(xintercept = 0, color = "grey") +
theme_bw() +
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank())
ggsave("surp_maringals.png", width = 8, height = 1)
word_norm %>%
ggplot(aes(x = psychoword, y = norm_surp, color = model)) +
theme_bw() +
facet_grid(. ~ corpus, scales = "free") +
#geom_rug(alpha = 0.003, sides = "b") +
geom_hline(yintercept=0, color = "blue") +
geom_vline(xintercept = 0, color = "grey") +
geom_smooth(se = T, alpha = 0.2) +
#coord_cartesian(ylim = c(-0.05, 0.1), xlim = c(-2, 3)) +
theme(legend.position = "bottom")
#ggsave( "./resid_length.png", height = 4, width = 8)
word_norm %>%
ggplot(aes(x = norm_surp, y = delta_log_lik, color = model)) +
theme_bw() +
facet_grid( . ~ corpus, scales = "free") +
#geom_rug(alpha = 0.003, sides = "b") +
geom_hline(yintercept=0, color = "blue") +
geom_vline(xintercept = 0, color = "grey") +
geom_smooth(se = T, alpha = 0.2) +
coord_cartesian(ylim = c(-0.05, 0.07), xlim = c(-2, 5)) +
theme(legend.position = "bottom")
ggsave( "./norm_surp.png", height = 4, width = 8)
ngram_highsurp = word_norm %>%
ungroup() %>%
filter(corpus == "dundee", norm_surp > 2, model == "5gram") %>%
select(code)
ngram_highsurp = ngram_highsurp$code
z = word_norm %>%
ungroup() %>%
filter(! code %in% ngram_highsurp) %>%
filter(corpus == "dundee")
write.csv(z, "ngram-ablate.csv")